﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Project.WebAPI.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private readonly IHostEnvironment hostingEnvironment;
        private readonly ILogger<GlobalExceptionFilterAttribute> logger;

        public GlobalExceptionFilterAttribute(IHostEnvironment hostingEnvironment, 
            ILogger<GlobalExceptionFilterAttribute> logger)
        {
            this.hostingEnvironment = hostingEnvironment;
            this.logger = logger;
        }

        /// <summary>
        /// 全局异常队列
        /// </summary>
        public static Queue<Exception> ExceptionsQueue = new Queue<Exception>();


        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            // 在此记录日志有可能会影响响应性能，故暂且存入队列
            ExceptionsQueue.Enqueue(context.Exception); // 入队

            //拦截处理
            if (!context.ExceptionHandled)
            {
                if (!hostingEnvironment.IsProduction())
                {
                    context.Result = new JsonResult(new
                    {
                        success = false,
                        code = 500,
                        msg = context.Exception.Message
                    });
                }
                else
                {
                    context.Result = new JsonResult(new
                    {
                        success = false,
                        code = 500,
                        msg = "服务器错误！"
                    });
                }
                 context.ExceptionHandled = true; // 标记错误被处理
            }
        }

    }
}
